import React, {Component} from 'react';
import {connect} from 'dva';
import {
  Form,
  Input,
  Button,
  Icon,
  Select,
  Tag,
  Popover,
  Modal,
  message,
  Cascader
} from 'antd';
import {
  taskManagementList, //获取任务列表
  taskGetIndustriesList, //获取任务类型
  taskDeleteTaskById,//删除任务
  taskDeleteTask,
  taskDoneTask,
  taskCancelTask,
  taskTreeTaskType
} from "../../services/api";
import './Task.less';
import TaskItem from "./TaskItem";
import bcx_utils from "../../common/bcx_utils";
import PSelect from "../../components/Pro/PSelect";
import PCascader from "../../components/Pro/PCascader";

const confirm = Modal.confirm;
const FormItem = Form.Item;
const {Option} = Select;


@connect(state => ({profile: state.profile}))

@Form.create()

export default class TaskList extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      expand: false,
      taskList: [],
      isLastPage: 0,
      cascaderOptions: [],//任务级联数据
      param: {
        pageSize: 10,
        pageNumber: 1,
        taskStatus: '',
        taskName: '',
        taskType: '',
        attendType: '',
        taskNature: '',
        taskAddress: ''
      },

    };
  }

  /************************生命周期********************************* */

  componentDidMount() {
    this.getTaskManagementList(); //获取任务列表
    this.taskTreeTaskType();
  }

  /************************ajax请求********************************* */
    //获取任务列表，
    //若 num 为0，请求的数据 替换 旧数据;
    //若 num 为1，则请求的数据继续 增加 在原有数据上
  getTaskManagementList = (num = 0, resolve) => {


    let param = {...this.state.param};
    console.log('getTaskManagementList-param', param);

    //增加新的分页数据
    if (num === 1) {
      param = {...param, ...{pageNumber: ++param.pageNumber}};
      this.setState({param});
    }


    //过滤 请求参数
    let checkParam = {};
    for (let key in param) {
      if (param[key] != '' && param[key] != undefined) {
        checkParam[key] = param[key];
      }
    }

    taskManagementList({
      ...checkParam
    }).then((res) => {
      console.log('获取任务列表', res)
      let taskList = [];

      //判断 分页数据新增 还是 搜索条件更改后替换
      if (num === 0) {
        taskList = res.data.data;
      }
      if (num === 1) {
        taskList = this.state.taskList.concat(res.data.data);
      }

      this.saveList(taskList, res);

      resolve && resolve();
    }, (err) => {
      console.log("获取任务列表失败:", err);
      resolve && resolve();
    });
  }
  //获取所有大小任务类型树形
  taskTreeTaskType = () => {
    taskTreeTaskType().then(({data = []}) => {
      console.log("获取所有大小任务类型树形", data);
      let newData = JSON.stringify(data);
      newData = newData.replace(/bigKey/g, "key");
      newData = newData.replace(/bigValue/g, "value");
      newData = newData.replace(/value/g, "label");
      newData = newData.replace(/key/g, "value");
      newData = JSON.parse(newData);
      console.log(newData);
      this.setState({cascaderOptions: newData});
    }, (err) => {
      console.log(err);
    });
  }


  //存储列表数据
  saveList = (taskList, res) => {
    this.setState({taskList});
    //判断是否最后一页（是否到底）
    if (res.data.totalPage === this.state.param.pageNumber) {
      this.setState({isLastPage: 1});
    }
  }

  // 按照之前的分页请求
  getOldPage = () => {
    const param = this.state.param;
    const {pageSize, pageNumber} = this.state.param;
    const oldPageParam = {...param, pageNumber: 1, pageSize: pageSize * pageNumber};

    taskManagementList(oldPageParam).then((res) => {
      const taskList = res.data.data;
      this.saveList(taskList, res);
    }, (err) => {
      console.log("获取任务列表失败:", err);
      resolve && resolve();
    });
  }


  //加载更多，防止重复提交
  loadMore = (num) => {
    bcx_utils.preventRA((resolve) => {
      this.getTaskManagementList(num, resolve);
    });
  }


  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values.pageNumber = 1;
        values.pageSize = this.state.param.pageSize;
        if (values.taskAddress != undefined) {
          values.province = values.taskAddress[0];
          values.city = values.taskAddress[1];
          values.area = values.taskAddress[2];
        }
        values.taskType = values.taskType[1]
        console.log(values);
        const param = {
          ...values
        };
        console.log('Received values of form: ', values);
        this.setState({param}, () => {
          this.loadMore(0);
        });
      }
    });
  }
  /************************方法********************************* */
  toggle = () => {
    const {expand} = this.state;
    this.setState({
      expand: !expand
    });
  }
  deleteTask = (dataSource, action, index) => {
    const that = this;
    let title = '';
    //关闭
    if (action === "close") {
      dataSource.taskStatus == '已完成'
        ? (title = '恭喜本次任务已圆满结束')
        : (title = "任务正在执行，是否确定提前结束任务？");
    }
    //取消
    else if (action === "cancel") {
      title = "确定取消本次任务？";
    }
    //删除
    else if (action === "delete") {
      title = "确定删除本次任务？";
    }
    //继续创建
    else if (action === 'goOn') {
      this.turnPage(dataSource);
      return;
    }

    const ajax = {
      "cancel": taskCancelTask,
      "delete": taskCancelTask,
      "close": taskCancelTask,
    };


    confirm({
      title,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        ajax[action]({comTaskId: dataSource.comTaskId}).then((res) => {
          console.log("删除任务res", res);
          that.getOldPage();
        }, (err) => {
          console.log('删除任务err：', err);
        })
      },
      onCancel() {
      },
    });
  };

  setSelectTaskType = () => {
    let taskType = this.state.taskType;
    const options = taskType.map((item, index) => {
      return <Option value={item.codeValue} key={index}>{item.label}</Option>
    })
    return options;
  }
  turnPage = (task) => {
    const {isFormal, comTaskId} = task;
    if (isFormal !== "0") {
      this.props.history.push(`/taskmanager/taskDetail?id=${comTaskId + ""}`);
    } else {
      this.props.history.push(`/taskmanager/newtask?id=${comTaskId + ""}`);
    }
  }
  renderTaskList = () => {
    const items = this.state.taskList.map(
      (item, index) => {
        return (
          <TaskItem
            key={index}
            number={index}
            dataSource={item}
            method={this.deleteTask}
            turnPage={this.turnPage}
          />);
      })
    return items;
  };
  // changeProvinceValue = (value, array) => {
  //   console.log(value, array);
  // }
  render() {
    const {getFieldDecorator, getFieldError, isFieldTouched} = this.props.form;
    const {expand, cascaderOptions} = this.state;
    // Only show error after a field is touched.
    return (

      <div className="Task">
        <Form layout="inline" onSubmit={this.handleSubmit}>
          <div className="Taskk">
            <FormItem label="任务名称" style={{marginTop: 0}}>
              {getFieldDecorator('taskName')(<Input placeholder="请输入"/>)}
            </FormItem>
            <FormItem label="任务状态" style={{marginTop: 0}}>
              {getFieldDecorator('taskStatus')(
                <PSelect
                  type="taskStatus"
                  style={{
                    width: 174
                  }}
                  addOption/>
              )}
            </FormItem>
            <span className="collape" onClick={this.toggle}>
              展开
              <Icon type={expand ? 'up' : 'down'}/>
            </span>
            <FormItem style={{marginTop: 0}}>
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
            </FormItem>
          </div>

          <div
            style={{
              display: `${expand
                ? "block"
                : "none"}`
            }}>
            <FormItem label="任务类型">
              {getFieldDecorator('taskType')(
                <Cascader options={cascaderOptions} placeholder="请输入"/>
              )}
            </FormItem>
            <FormItem label="出勤方式">
              {getFieldDecorator('attendType')(
                <PSelect
                  type="attendType"
                  style={{
                    width: 174
                  }}
                  addOption/>)}
            </FormItem>
            <FormItem label="任务地点">
              {getFieldDecorator('taskAddress')(<PCascader placeholder="请选择"/>)}
            </FormItem>
            <FormItem label="任务性质">
              {getFieldDecorator('taskNature')(
                <PSelect
                  type="taskNature"
                  style={{
                    width: 174
                  }}
                  addOption/>
              )}
            </FormItem>
          </div>

        </Form>
        <div className="cartlist">
          <div
            className="cart-item cart-item-add"
            style={{
              cursor: "pointer"
            }}
            onClick={() => {
              this
                .props
                .history
                .push('/taskmanager/newtask')
            }}>
            <Icon style={{
              fontSize: 28
            }} type="plus"/>
            新增任务
          </div>
          {this.renderTaskList()}
        </div>
        {this.state.isLastPage === 0
          ? <div className="more" onClick={this.loadMore.bind(this, 1)}>加载更多</div>
          : <div className="more">~我是有底线的~</div>}
      </div>
    );
  }
}
